<?php

namespace App\Http\Controllers;

use App\Models\DoctorModel;
use App\Models\DoctorPatientModel;
use App\Models\PatientModel;
use EasyWeChat\Kernel\Support\File;
use GuzzleHttp\Client;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use EasyWeChat\Work\GroupRobot\Messages\Markdown;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Symfony\Component\Cache\Adapter\RedisAdapter;

class DataBaseController extends Controller
{

    protected $servers = ['oms_test', 'oms_prod', 'dps_test', 'dps_prod'];
    public function index()
    {
        return view('database.index');
    }

    public function delPatient()
    {
        if (\request()->method() == 'GET') {
            return view('database.patient');
        } elseif (\request()->method() == 'POST') {
            try {

                $server = \request()->post('mysql_server');
                $mobile = \request()->post('mobile');
                $pwd = \request()->post('pwd');
                // if ($pwd != 'dtrd2022!') throw new \Exception('没有执行权限');
                if (!in_array($server, $this->servers)) throw new \Exception('未知服务器');

                $patient = DB::connection($server)->select("select data_id , patients_name from dtrd_ent_rd_patient where patients_mobile in (".$mobile.")");
                if (is_null($patient)) throw new \Exception('未找到该患者相关信息');

                $ids = Arr::pluck($patient, 'data_id');
                $idstr = implode(',', $ids);

                Redis::hset('database-delete:patient', $server.'-'.time(), json_encode(['mobile'=>$mobile,'server'=>$server,'time' => date('Y-m-d H:i:s'),'ip' => \request()->ip()]));

                DB::beginTransaction();
                DB::connection($server)->update("update dtrd_rl_doctor_patient set is_del = 1 where patient_id in ({$idstr})");
                DB::connection($server)->update("update dtrd_ent_rd_archive_basic set is_del = 1 where patient_id in ({$idstr})");
                DB::connection($server)->update("update dtrd_ent_rd_archive_overview set is_del = 1 where patient_id in ({$idstr})");
                DB::connection($server)->update("update dtrd_ent_rd_archive_physical set is_del = 1 where patient_id in ({$idstr})");
                DB::connection($server)->update("update dtrd_rl_package_patient set is_del = 1 where patient_id in ({$idstr})");
                DB::connection($server)->update("update dtrd_rl_patient_service_detail set is_del = 1 where patient_id in ({$idstr})");
                DB::connection($server)->update("update dtrd_ent_rd_archive_reverse_scheme set is_del = 1 where patient_id in ({$idstr})");
                DB::connection($server)->update("update dtrd_ent_rd_patient set is_del = 1 where data_id in ($idstr)");

                $message = ['code' => 0, 'msg' => 'ok', 'data' => $patient];
            } catch (\Exception $e) {
                DB::rollBack();
                $message = ['code' => -1, 'msg' => $e->getMessage()];
            }
            DB::commit();
            return json_encode($message);
        }
        return 'error';
    }

    public function getPackages()
    {
        $server = \request()->get('mysql_server');
        $result = DB::connection($server)->select("select * from dtrd_ent_rd_service_package where is_del = 0");
        $data = [
            'code' => 0,
            'data' => $result
        ];
        return json_encode($data);
    }

    public function delPackage()
    {
        if (\request()->method() == 'GET') {
            return view('database.package');
        } elseif (\request()->method() == 'POST') {
            try {
                $server = \request()->post('mysql_server');
                $packageId = \request()->post('package_id');
                $pwd = \request()->post('pwd');
                // if ($pwd != 'dtrd2022!') throw new \Exception('没有执行权限');
                if (!in_array($server, $this->servers)) throw new \Exception('未知服务器');
                if (is_null($packageId)) throw new \Exception('参数错误');

                Redis::hset('database-delete:package', $server.'-'.time(), json_encode(['package_id'=>$packageId,'server'=>$server,'time' => date('Y-m-d H:i:s'),'ip' => \request()->ip()]));

                DB::beginTransaction();
                DB::connection($server)->update("UPDATE dtrd_ent_rd_service_package SET is_del = 1 WHERE data_id in ({$packageId})");
                DB::connection($server)->update("UPDATE dtrd_rl_package_patient SET is_del = 1 WHERE package_id in ({$packageId})");
                DB::connection($server)->update("UPDATE dtrd_rl_patient_service_detail SET is_del = 1 WHERE package_id in ({$packageId})");
                DB::connection($server)->update("UPDATE dtrd_ent_rd_archive_reverse_scheme SET is_del = 1 WHERE service_template_id in ({$packageId})");
                DB::connection($server)->update("UPDATE dtrd_rl_service_package SET is_del = 1 WHERE package_id in ({$packageId})");

                $message = ['code' => 0, 'msg' => 'ok'];
            } catch (\Exception $e) {
                DB::rollBack();
                $message = ['code' => -1, 'msg' => $e->getMessage()];
            }
            DB::commit();
            return json_encode($message);
        }
        return 'error';
    }

    public function getFlup()
    {
        $server = \request()->get('mysql_server');
        $result = DB::connection($server)->select("select * from dtrd_ent_rd_flup_template_project where is_del = 0");
        $data = [
            'code' => 0,
            'data' => $result
        ];
        return json_encode($data);
    }

    public function delFlup()
    {
        if (\request()->method() == 'GET') {
            return view('database.flup');
        } elseif (\request()->method() == 'POST') {
            try {
                $server = \request()->post('mysql_server');
                $dataId = \request()->post('data_id');
                $pwd = \request()->post('pwd');
                // if ($pwd != 'dtrd2022!') throw new \Exception('没有执行权限');
                if (!in_array($server, $this->servers)) throw new \Exception('未知服务器');
                if (is_null($dataId)) throw new \Exception('参数错误');

                Redis::hset('database-delete:flup', $server.'-'.time(), json_encode(['data_id'=>$dataId,'server'=>$server,'time' => date('Y-m-d H:i:s'),'ip' => \request()->ip()]));

                DB::beginTransaction();
                DB::connection($server)->update("UPDATE dtrd_ent_rd_flup_template_project SET is_del = 1 WHERE data_id in ({$dataId})");
                DB::connection($server)->update("UPDATE dtrd_rl_flup_project_record SET is_del = 1 WHERE project_id in ({$dataId})");
                DB::connection($server)->update("UPDATE dtrd_rl_flup_template_project SET is_del = 1 WHERE template_project_id in ({$dataId})");

                $message = ['code' => 0, 'msg' => 'ok'];
            } catch (\Exception $e) {
                DB::rollBack();
                $message = ['code' => -1, 'msg' => $e->getMessage()];
            }
            DB::commit();
            return json_encode($message);
        }
        return 'error';
    }

    public function getSignin()
    {
        $server = \request()->get('mysql_server');
        $result = DB::connection($server)->select("select * from dtrd_ent_rd_signin_template where is_del = 0");
        $data = [
            'code' => 0,
            'data' => $result
        ];
        return json_encode($data);
    }

    public function delSignin()
    {
        if (\request()->method() == 'GET') {
            return view('database.signin');
        } elseif (\request()->method() == 'POST') {
            try {
                $server = \request()->post('mysql_server');
                $dataId = \request()->post('data_id');
                $pwd = \request()->post('pwd');
                // if ($pwd != 'dtrd2022!') throw new \Exception('没有执行权限');
                if (!in_array($server, $this->servers)) throw new \Exception('未知服务器');
                if (is_null($dataId)) throw new \Exception('参数错误');

                Redis::hset('database-delete:signin', $server.'-'.time(), json_encode(['data_id'=>$dataId,'server'=>$server,'time' => date('Y-m-d H:i:s'),'ip' => \request()->ip()]));

                DB::beginTransaction();
                DB::connection($server)->update("UPDATE dtrd_ent_rd_signin_template SET is_del = 1 WHERE data_id in ({$dataId})");
                DB::connection($server)->update("UPDATE dtrd_ent_rd_signin_plan SET is_del = 1 WHERE sign_in_template_id in ({$dataId})");

                $message = ['code' => 0, 'msg' => 'ok'];
            } catch (\Exception $e) {
                DB::rollBack();
                $message = ['code' => -1, 'msg' => $e->getMessage()];
            }
            DB::commit();
            return json_encode($message);
        }
        return 'error';
    }

    public function delDoctor()
    {
        if (\request()->method() == 'GET') {
            return view('database.doctor');
        } elseif (\request()->method() == 'POST') {
            try {

                $server = \request()->post('mysql_server');
                $mobile = \request()->post('mobile');
                $pwd = \request()->post('pwd');
                // if ($pwd != 'dtrd2022!') throw new \Exception('没有执行权限');
                if (!in_array($server, $this->servers)) throw new \Exception('未知服务器');

                $patient = DB::connection($server)->select("select data_id , doctors_name from dtrd_ent_rd_doctor where doctors_mobile in (".$mobile.")");
                if (is_null($patient)) throw new \Exception('未找到该医生相关信息');

                $ids = Arr::pluck($patient, 'data_id');
                $idstr = implode(',', $ids);

                Redis::hset('database-delete:doctor', $server.'-'.time(), json_encode(['mobile'=>$mobile,'server'=>$server,'time' => date('Y-m-d H:i:s'),'ip' => \request()->ip()]));

                DB::beginTransaction();
                DB::connection($server)->update("update dtrd_ent_rd_doctor set is_del = 1 where data_id in ({$idstr})");
                DB::connection($server)->update("update dtrd_ent_rd_doctor_team set is_del = 1 where manage_doctor_id in ({$idstr})");
                DB::connection($server)->update("update dtrd_ent_rd_doctor_statistic_info set is_del = 1 where doctor_id in ({$idstr})");
                DB::connection($server)->update("update dtrd_rl_doctor_team_doctor set is_del = 1 where doctor_id in ({$idstr})");
                DB::connection($server)->update("update dtrd_rl_doctor_patient set is_del = 1 where doctor_id in ({$idstr})");
                DB::connection($server)->update("update dtrd_ent_rd_doctor_signin_suggest set is_del = 1 where doctor_id in ({$idstr})");
                DB::connection($server)->update("update dtrd_ent_rd_signin_record_suggest set is_del = 1 where suggest_doctor_id in ({$idstr})");
                DB::connection($server)->update("update dtrd_ent_rd_patient set doctor_id = null where doctor_id in ($idstr)");

                $message = ['code' => 0, 'msg' => 'ok', 'data' => $patient];
            } catch (\Exception $e) {
                DB::rollBack();
                $message = ['code' => -1, 'msg' => $e->getMessage()];
            }
            DB::commit();
            return json_encode($message);
        }
        return 'error';
    }

}
